package com.banciyuan.bcywebview.biz.setting;


import android.content.Context;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.api.SpaceApi;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.AppSetting;

public class MainSettingHelper {

    public static String TYPE_DRAWER = "drawer";
    public static String TYPE_WRITER = "writer";
    public static String TYPE_COSER = "coser";
    public static String TYPE_DAILY = "daily";
    public static String TYPE_USER_TUIJIAN = "user_tuijian";
    public static String TYPE_GROUP = "group";
    public static String TYPE_GROUP_POST = "group_post";
    public static String TYPE_ZHIPIN = "zhipin";
    public static String TYPE_TRAITOR = "traitor";


    private static void storeLastTraitorSetting(Context context) {
        long currentTime = System.currentTimeMillis();
        SPHelper.putLong(context, SPConstant.SPNAME_TRAITOR, SPConstant.LAST_TRAITOR_TIME + UserDataHelper.getInstance(context).getUid(), currentTime);
    }

    private static boolean traitorBeyondTwoHours(Context context) {
        long currentTime = System.currentTimeMillis();
        long lastTime = SPHelper.getLong(context, SPConstant.SPNAME_TRAITOR, SPConstant.LAST_TRAITOR_TIME + UserDataHelper.getInstance(context).getUid(), currentTime);
        return currentTime - lastTime > 2 * 3600 * 1000;
    }

    public static void setMainSetting(final Context context, final String type, final int is_open, final MainSettingListener mainSettingListener) {
        String url = HttpUtils.BASE_URL + SpaceApi.getSettimeline();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(context).getToken()));
        pairs.add(new BcyPair(HttpUtils.TYPE, type));
        pairs.add(new BcyPair("is_open", String.valueOf(is_open)));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, context)) {
                    if (TYPE_TRAITOR.equals(type)) {
                        if (is_open == 1) {
                            storeLastTraitorSetting(context);
                        } else {
                            BaseObserver.getInstance().notifyWatchers(BaseObserver.MAINSETTING_UNNOTICE_EVENT);
                        }
                    }
                    mainSettingListener.setMainSettingSuccess(response);
                } else {
                    mainSettingListener.onFail();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mainSettingListener.onFail();
            }
        };

        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        VolleyQueue.getRquest(context).add(param);
    }


    public static void getMainSettings(final Context context, final MainSettingListener mainSettingListener) {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(context).getToken()));
        paramsList.add(new BcyPair(HttpUtils.STYPE, "timeline"));
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, context)) {
                    JSONObject result = null;
                    try {
                        result = new JSONObject(response);
                        JSONObject jsonObject = result.getJSONObject(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        AppSetting appSetting = gson.fromJson(jsonObject.toString(), AppSetting.class);
                        if (isTraitorMode(appSetting) && traitorBeyondTwoHours(context)) {
                            BaseObserver.getInstance().notifyWatchers(BaseObserver.MAINSETTING_NOTICE_EVENT);
                        }
                        mainSettingListener.getMainSettingSuccess(appSetting);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    mainSettingListener.onFail();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mainSettingListener.onFail();
            }
        };
        String url = HttpUtils.BASE_URL + SpaceApi.getSettings();
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSuccess, url, context, null);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, params, onSuccess, errorProxy);
        VolleyQueue.getRquest(context).add(getUserdataRequest);
    }

    private static boolean isTraitorMode(AppSetting appSetting) {
        return null != appSetting && null != appSetting.getTimeline() && appSetting.getTimeline().getTraitor() == 1;
    }

    public interface MainSettingListener {
        void getMainSettingSuccess(AppSetting appSetting);

        void setMainSettingSuccess(String response);

        void onFail();
    }
}
